import { useState, useCallback } from 'react';

const getApiUrl = () => {
    const url = `${process.env.REACT_APP_API_URL}/api/nonogram`;
    console.log('API地址:', url);
    return url;
};

const API_URL = getApiUrl();

const fetchWithTimeout = async (url, options = {}, timeout = 8000) => {
    console.log(`发起请求: ${url}`, options);
    
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), timeout);

    try {
        const response = await fetch(url, {
            ...options,
            mode: 'cors',
            credentials: 'omit',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                ...(options.headers || {})
            },
            signal: controller.signal
        });

        clearTimeout(timeoutId);
        
        if (!response.ok) {
            const errorData = await response.json().catch(() => ({}));
            throw new Error(errorData.error || `HTTP错误! 状态: ${response.status}`);
        }

        return response;
    } catch (error) {
        clearTimeout(timeoutId);
        console.error('请求失败:', error);
        throw error;
    }
};

export function useGame() {
    const [grid, setGrid] = useState([]);
    const [rowHints, setRowHints] = useState([]);
    const [colHints, setColHints] = useState([]);
    const [gameStarted, setGameStarted] = useState(false);
    const [message, setMessage] = useState('');
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);
    const [timePlayed, setTimePlayed] = useState(0);
    const [difficulty, setDifficulty] = useState(5);
    const [hintsLeft, setHintsLeft] = useState(0);
    const [solution, setSolution] = useState(null);

    const getInitialHints = useCallback((size) => {
        if (size === 5) return 10;      // 简单模式 3 次提示
        if (size === 10) return 5;     // 中等模式 5 次提示
        if (size === 15) return 8;     // 困难模式 8 次提示
        return 3;
    }, []);

    const startNewGame = useCallback(async () => {
        setLoading(true);
        setError(null);
        
        try {
            const response = await fetchWithTimeout(
                `${API_URL}/new-game`,
                {
                    method: 'POST',
                    body: JSON.stringify({ size: difficulty })
                }
            );
            
            const data = await response.json();
            
            setGrid(Array(data.height).fill().map(() => Array(data.width).fill(0)));
            setRowHints(data.rowHints);
            setColHints(data.colHints);
            setSolution(data.solution);
            setGameStarted(true);
            setMessage('');
            setTimePlayed(0);
            setHintsLeft(getInitialHints(difficulty));
        } catch (error) {
            console.error('游戏启动失败:', error);
            setError('启动游戏时出错：' + error.message);
        } finally {
            setLoading(false);
        }
    }, [difficulty, getInitialHints]);

    const getHint = useCallback(() => {
        if (hintsLeft <= 0 || !solution || !grid) return;

        const emptyOrWrongCells = [];
        for (let i = 0; i < grid.length; i++) {
            for (let j = 0; j < grid[i].length; j++) {
                if (grid[i][j] !== solution[i][j]) {
                    emptyOrWrongCells.push([i, j]);
                }
            }
        }

        if (emptyOrWrongCells.length > 0) {
            const [row, col] = emptyOrWrongCells[
                Math.floor(Math.random() * emptyOrWrongCells.length)
            ];
            
            setGrid(prevGrid => {
                const newGrid = [...prevGrid];
                newGrid[row] = [...newGrid[row]];
                newGrid[row][col] = solution[row][col];
                return newGrid;
            });
            
            setHintsLeft(prev => prev - 1);
            setMessage(`提示：第${row + 1}行第${col + 1}列应该是${solution[row][col] ? '填充' : '空白'}的`);
        }
    }, [hintsLeft, solution, grid]);

    const checkSolution = useCallback(async () => {
        try {
            const response = await fetchWithTimeout(
                `${API_URL}/check-solution`,
                {
                    method: 'POST',
                    body: JSON.stringify({ grid })
                }
            );
            
            if (!response.ok) {
                const errorData = await response.json().catch(() => ({}));
                throw new Error(errorData.error || '检查答案失败');
            }
            
            const data = await response.json();
            
            setMessage(data.correct 
                ? `恭喜！你用时${data.timePlayed}秒解开了这个谜题！` 
                : '还没有完全正确，请继续尝试！'
            );
            
            if (data.correct) {
                setTimePlayed(data.timePlayed);
            }
        } catch (error) {
            console.error('检查答案错误:', error);
            setError('检查答案时出错：' + (error.message || '网络错误'));
        }
    }, [grid]);

    return {
        grid,
        setGrid,
        rowHints,
        colHints,
        gameStarted,
        message,
        loading,
        error,
        timePlayed,
        difficulty,
        setDifficulty,
        hintsLeft,
        startNewGame,
        checkSolution,
        getHint
    };
} 